using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace UFrame
{
    public class Gradient : BaseMeshEffect
    {
        public Color32 leftColor = Color.white;
        public Color32 rightColor = Color.black;

        public override void ModifyMesh(VertexHelper vh)
        {
            if (!IsActive())
            {
                return;
            }

            var count = vh.currentVertCount;
            if (count == 0)
            {
                return;
            }

            var vertexs = new List<UIVertex>();
            for (var i = 0; i < count; i++)
            {
                var vertex = new UIVertex();
                vh.PopulateUIVertex(ref vertex, i);
                vertexs.Add(vertex);
            }

            var left = vertexs[0].position.x;
            var right = vertexs[vertexs.Count - 1].position.x;

            for (var i = 1; i < count; i++)
            {
                var x = vertexs[i].position.x;
                if (x > right)
                {
                    right = x;
                }
                else if (x < left)
                {
                    left = x;
                }
            }

            var width = right - left;
            for (var i = 0; i < count; i++)
            {
                var vertex = vertexs[i];

                var color = Color32.Lerp(leftColor, rightColor, Mathf.Clamp01(vertex.position.x - left / width));

                vertex.color = color;

                vh.SetUIVertex(vertex, i);
            }
        }
    }
}

